package iot.wlink.network.protocols.mqtt;

import iot.wlink.network.handler.DataStreamHandler;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.iot.mqtt.codec.ByteBufferUtil;
import net.dreamlu.iot.mqtt.codec.MqttQoS;
import net.dreamlu.iot.mqtt.core.server.event.IMqttMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.ByteBuffer;

/**
 * @author : willian fu
 * @date : 2021/8/21
 * 消息监听器
 */
@Slf4j
@Component
public class MqttMessageListener implements IMqttMessageListener {

    @Autowired
    private MqttDeviceManager manager;

    @Autowired
    private DataStreamHandler handler;

    @Override
    public void onMessage(String clientId, String topic, MqttQoS mqttQoS, ByteBuffer byteBuffer) {
        //收到消息后由脚本引擎解析
        byte[] bytes = new byte[byteBuffer.limit()];
        byteBuffer.get(bytes);
        handler.handler(manager.decode(clientId, bytes));
        log.info("收到[{}]来自[{}]的mqtt消息", topic, clientId);
    }
}
